package com.jacklin.snowy.limitstrategy.factory;

import com.jacklin.snowy.limitstrategy.enums.RequestLimitType;
import com.jacklin.snowy.limitstrategy.service.RequestLimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 限流工厂类
 *
 * @author: jacklin
 * @since: 2022/5/10 12:02
 */
@Slf4j
@Component
public class RequestLimitFactory implements ApplicationContextAware {

    private static final Map<RequestLimitType, RequestLimitService> MAP = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        try {
            applicationContext.getBeansOfType(RequestLimitService.class).values().forEach(service -> MAP.put(service.getType(), service));
        } catch (Exception e) {
            log.error("初始化限流策略异常", e);
        }
    }

    /**
     * 构建service
     *
     * @param type 限流类型
     * @return 限流操作类
     **/
    public RequestLimitService build(RequestLimitType type) {
        return MAP.get(type);
    }
}
